<?php
require_once ROOT_PATH . '/core/Container.php';
require_once ROOT_PATH . '/core/Router.php';
require_once ROOT_PATH . '/core/Controller.php';
require_once ROOT_PATH . '/core/Model.php';
require_once ROOT_PATH . '/core/Database.php';

class App {
    protected $container;
    protected $router;
    
    public function __construct() {
        // 确保APP_ROOT常量已定义
        if (!defined('APP_ROOT')) {
            define('APP_ROOT', dirname(__DIR__));
        }
        
        // 创建服务容器
        $this->container = new Container();
        
        // 注册核心服务
        $this->registerServices();
        
        // 获取路由实例
        $this->router = $this->container->make('Router');
        
        // 注册路由
        $this->registerRoutes();
    }
    
    protected function registerServices() {
        // 注册数据库服务
        $this->container->singleton('Database', function($container) {
            $config = require ROOT_PATH . '/config/database.php';
            return new Database($config);
        });
        
        // 注册路由服务
        $this->container->singleton('Router', 'Router');
        
        // 注册控制器工厂
        $this->container->bind('ControllerFactory', function($container) {
            return function($controllerName) use ($container) {
                $controllerFile = ROOT_PATH . '/app/controllers/' . $controllerName . '.php';
                
                if (file_exists($controllerFile)) {
                    require_once $controllerFile;
                    return $container->make($controllerName);
                }
                
                throw new Exception("控制器 {$controllerName} 不存在");
            };
        });
    }
    
    protected function registerRoutes() {
        // 获取路由实例
        $router = $this->container->make('Router');
        
        // 注册路由
        $router->add('/', 'HomeController', 'index');
        $router->add('/users', 'UserController', 'list');
        $router->add('/user/detail', 'UserController', 'detail');
    }
    
    public function run() {
        try {
            // 获取当前URL路径
            $url = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
            
            // 获取路由实例
            $router = $this->container->make('Router');
            
            // 分发请求
            $router->dispatch($url, $this->container);
        } catch (Exception $e) {
            echo "应用错误: " . $e->getMessage();
        }
    }
    
    // 获取容器实例
    public function getContainer() {
        return $this->container;
    }
}
?>